package za.co.dylanjaneke.airdownloader.command
{
	import air.update.ApplicationUpdaterUI;
	import air.update.events.UpdateEvent;
	
	import flash.events.ErrorEvent;
	import flash.events.Event;
	
	import mx.controls.Alert;
	
	import za.co.dylanjaneke.airdownloader.events.CheckForUpdateEvent;
	import za.co.dylanjaneke.airdownloader.model.StatusPM;

	/**
	 * Author:Dylan Janeke
	 */
	[Name("checkForUpdateCommand")]
	public class CheckForUpdateCommand
	{
		protected var appUpdater:ApplicationUpdaterUI = 
			new ApplicationUpdaterUI();
		
		[Inject]
		public var statusPM:StatusPM;
		
		[Observer]
		public function handleCheckForUpdateEvent(event:CheckForUpdateEvent): void
		{
			statusPM.status = "checking for updates...";
			appUpdater.updateURL= "http://vicariousdownloader.googlecode.com/files/update.xml";
			appUpdater.addEventListener(UpdateEvent.INITIALIZED, onInit);
			appUpdater.addEventListener(UpdateEvent.DOWNLOAD_START, onDownloadStart);
			appUpdater.addEventListener(UpdateEvent.BEFORE_INSTALL, onBeforeUpdateInstall);
			appUpdater.addEventListener(UpdateEvent.DOWNLOAD_COMPLETE, onDownloadComplete);
			appUpdater.addEventListener(ErrorEvent.ERROR, onUpdaterError);
						
			appUpdater.isCheckForUpdateVisible = false;
			appUpdater.initialize();
		}
		
		protected function onInit(event:UpdateEvent):void 
		{
			appUpdater.checkNow();
		}
		
		protected function onDownloadStart(event:UpdateEvent): void
		{
			statusPM.status= "downloading update...";	
		}
		
		protected function onBeforeUpdateInstall(event:UpdateEvent): void
		{
			statusPM.status= "new update available.";
		}
		
		protected function onDownloadComplete(event:UpdateEvent): void
		{
			statusPM.status= "update download completed.";
		}
		
		protected function onUpdaterError(event:ErrorEvent):void
		{
			Alert.show(event.toString(), "Couldn't check for new updates.");
		}
	}
}